const express = require("express");
const app = express();
const fs = require("fs");

app.use("/", express.static('./public'))

app.use(express.urlencoded());
app.get("/", (req, res) => {
    res.send("express可以自动进行utf8处理");//输出一个字符串
})


app.get("/api/v1/pets", (req, res) => {
    const pets = JSON.parse(fs.readFileSync("./db/pets.json").toString());
    res.json(pets);
    // res.json([
    //     {
    //         id: 1,
    //         name: "暴龙兽",
    //     },
    //     {
    //         id: 2,
    //         name: "天使兽",
    //     },
    //     {
    //         id: 3,
    //         name: "亚古兽",
    //     },
    //     {
    //         id: 4,
    //         name: "加鲁鲁兽"
    //     },
    //     {
    //         id: 5,
    //         name: "仙人掌兽"
    //     }
    // ]
    // );
})

app.post("/api/v1/pets", (req, res) => {
    const pets = JSON.parse(fs.readFileSync("./db/pets.json").toString());
    //... js扩展运算符，可以实现对象的浅拷贝
    pets.push({ id: Date.now(), ...req.body });
    fs.writeFileSync("./db/pets.json", JSON.stringify(pets));
    res.json({
        code: 1,
        msg: "数据保存成功",
    })
    // res.redirect("/index.html");
})


app.delete("/api/v1/pets/:id", (req, res) => {
    const { id } = req.params;
    const pets = JSON.parse(fs.readFileSync("./db/pets.json").toString());
    const index = pets.findIndex((item) => item.id == id);
    pets.splice(index, 1);
    fs.writeFileSync("./db/pets.json", JSON.stringify(pets));
    res.json({
        code: 1,
        msg: "删除成功",
    })
})

app.put("/api/v1/pets/:id", (req, res) => {
    const { id } = req.params;
    const pets = JSON.parse(fs.readFileSync("./db/pets.json").toString());
    const index = pets.findIndex((item) => item.id == id);
    pets[index] = { ...{ id }, ...req.body };
    fs.writeFileSync("./db/pets.json", JSON.stringify(pets));

    res.json({
        code: 1,
        msg: "修改成功",
    })
})
app.listen(3333, () => {
    console.log("服务器运行在3333端口");
})